﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;


public partial class CheckYC : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userName"] == null || Session["roleID"] == null)
        {
            Response.Redirect("Login.aspx");
            Response.End();
        }        
        if (!Page.IsPostBack)
        {
            string YCID = Request.QueryString["ycid"].ToString();
            string userName = Session["userName"].ToString();
            string roleID = Session["roleID"].ToString();
            btnprintbill.Attributes.Add("onclick", "openfullscreen('printYCbill.aspx?ycid=" + YCID + "');");         
            if (roleID != "1")
            {
                if (!CheckRight(userName, YCID))
                {
                    Response.Write("<script language='javascript'>alert('对不起！您无权查看该异常');location.href='YCList.aspx'</script>");
                    Response.End();
                }
                chkFinish.Checked = false;
                chkFinish.Visible = false;
                btnprintbill.Visible = true;
                btnUpdate.Visible = false;
            }
            if (!CheckIsMyDuty(userName, YCID))
            {
                    txtAnnotate.Enabled = false;
                    ddlToDep.Enabled = false;
                    ddlToUserName.Enabled = false;
                    btnSubmit.Enabled = false;
                    chkFinish.Enabled = false;                
            }            
            BindYCData(YCID);
            BindToRpYCChekBill(YCID);
            BindToDdlDep();
            //ddlToDep.Attributes.Add("onchange", "send_request()");
            BindToDdlName(); 
        }
    }
    /// <summary>
    /// 判断用户是否有权查看当前异常
    /// </summary>
    /// <param name="userName">当前用户名</param>
    /// <param name="YCID">异常编号</param>
    /// <returns></returns>
    protected Boolean CheckRight(string userName, string YCID)
    {
        BasicClass BaseC = new BasicClass();
        int userDep = Convert.ToInt32(BaseC.GetDepIDByUserName(userName));
        YCDeal YCClass = new YCDeal();
        string crrentOperator = YCClass.GetCurrentOperator(YCID).ToLower();
        int YCUpDep = Convert.ToInt32(YCClass.GetUpYCDepIDByYCID(YCID).ToString());
        if (userDep == YCUpDep || crrentOperator==userName.ToLower() || YCClass.checkViewRight(YCID,userDep))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    /// <summary>
    /// 判断该异常是否是当前操作者处理的异常
    /// </summary>
    /// <param name="userName">当前操作者用户名</param>
    /// <param name="YCID">异常编号ID</param>
    /// <returns>是则返回true，否则返回false</returns>
    protected Boolean CheckIsMyDuty(string userName, string YCID)
    {
        Boolean check;
        string dataYear = YCID.Substring(2, 4);
        string tableName = "YCMS" + dataYear;
        string sqlString = "select count(*) from " + tableName + " where YCID='" + YCID + "' and CURRENTOPERATER='" + userName + "'";
        DBOperation DBO = new DBOperation();
        int count = Convert.ToInt32(DBO.ExcuteScalar(sqlString));
        if (count > 0)
        {
            check = true;
        }
        else
        {
            check = false;
        }
        return check;
    }
    /// <summary>
    /// 绑定显示数据
    /// </summary>
    protected void BindYCData(string YCID)
    {
        string YCId = YCID;
        string dataYear = YCId.Substring(2, 4);
        string tabName = "YCMS" + dataYear;
        string sqlString = "select * from " + tabName + " where YCID='" + YCId + "'";
        DBOperation DBO = new DBOperation();
        SqlDataReader sdr = DBO.GetDataReader(sqlString);
        if (sdr.Read())
        {
            lblYCID.Text = YCId;            
            lblDepName.Text = BasicClass.GetDepNameByDepID(sdr["DEPID"].ToString());
            string upUser=BasicClass.GetTrueNameByUserName(sdr["USERNAME"].ToString());
            lblUpUserName.Text = upUser;
            lblUpUser.Text = upUser;            
            DateTime addDate=Convert.ToDateTime(sdr["ADDDATE"].ToString());
            lblAddDate.Text = addDate.ToShortDateString();
            lblAddDate2.Text = addDate.ToShortDateString();
            lblYear.Text = addDate.Year.ToString();            
            lblContent.Text = sdr["CONTENT"].ToString();
            BasicClass tempGetDepName = new BasicClass();
            lblCurrentDep.Text = tempGetDepName.GetDepNameByUserName(sdr["CURRENTOPERATER"].ToString());
            if (sdr["STATUS"].ToString() == "1")
            {
                btnSubmit.Visible = false;
                PanelcheckForm.Visible = false;
                btnprintbill.Visible = true;
            }
            else
            {
                btnSubmit.Visible = true;
                PanelcheckForm.Visible = true;
                btnprintbill.Visible = true;
            }
        }
        //绑定相关附件
        string lblFilesText = "";
        string fileName = "";
        string filePath = "";
        Hashtable annexFiles = GetAnnexFiles(YCId);
        for (int i = 0; i < annexFiles.Count; i++)
        {
            if (annexFiles[i].ToString() != "")
            {
                fileName = annexFiles[i].ToString();
                fileName = fileName.Substring(fileName.LastIndexOf("\\") + 1);
                filePath = annexFiles[i].ToString();
                int item = i + 1;
                filePath = Server.UrlEncode(filePath);
                lblFilesText += item.ToString() + "、<img src='images/filePic.gif' /><a href='DownLoad.aspx?filepath=" + filePath + "' target='blank'>" + fileName + "</a>,&nbsp;&nbsp;&nbsp;&nbsp;";
            }
        }
        lblAnnexFiles.Text = lblFilesText;
        sdr.Close();

    }
    protected Hashtable GetAnnexFiles(string YCID)
    {
        Hashtable annexFiles = new Hashtable();
        string dataYear = YCID.Substring(2, 4);
        string tableName = "YCFILES" + dataYear;
        string sqlString = "select * from " + tableName + " where YCID='" + YCID + "'";
        DBOperation DBO = new DBOperation();
        SqlDataReader sdr = DBO.GetDataReader(sqlString);

        for (int i = 0; sdr.Read(); i++)
        {
            annexFiles[i] = sdr["FILENAME"].ToString();
        }
        sdr.Close();
        return annexFiles;
    }
    protected void BindToRpYCChekBill(string YCID)
    {
        string YCId = YCID;
        string currentYear = YCId.Substring(2, 4);
        string tabName = "YCSTEPS" + currentYear;
        DBOperation DBO = new DBOperation();
        string sqlstring = "select * from " + tabName + " where YCID='" + YCId + "' and SEQ<>'1' order by SEQ ASC,AUTOID ASC";
        DataSet ds = DBO.GetDataSet(sqlstring, "TEMP");
        rpYCCheckBill.DataSource = ds.Tables["TEMP"].DefaultView;
        rpYCCheckBill.DataBind();        

    }
    //绑定数据到DdlDep控件
    protected void BindToDdlDep()
    {
        DBOperation DBO = new DBOperation();
        string sqlString = "select DEPID,DEPNAME from DEPARTMENT where STATUS='1' order by DEPID ASC";
        SqlDataReader sdr = DBO.GetDataReader(sqlString);
        ddlToDep.DataSource = sdr;
        ddlToDep.DataTextField = "DEPNAME";
        ddlToDep.DataValueField = "DEPID";        
        ddlToDep.DataBind();
        ddlToDep.Items.Insert(0, new ListItem("请选择", "-1"));
        sdr.Close();

    }
    //绑定数据到DdlName控件
    protected void BindToDdlName()
    {
        DBOperation DBO = new DBOperation();
        string sqlString = "select TRUENAME,USERNAME from USERS where STATUS=1 and USERNAME<>'admin' and DEPID=" + ddlToDep.SelectedValue + " order by DEPID ASC";
        SqlDataReader sdr = DBO.GetDataReader(sqlString);
        ddlToUserName.DataSource = sdr;
        ddlToUserName.DataTextField = "TRUENAME";
        ddlToUserName.DataValueField = "USERNAME";        
        ddlToUserName.DataBind();
        ddlToUserName.Items.Insert(0, new ListItem("请选择", "-1"));
        sdr.Close();
    }
    //实现部门与人员的二级联动    
    protected void ddlToDep_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindToDdlName();
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string annotate = BasicClass.HtmlEncode(txtAnnotate.Text);
        string YCID = lblYCID.Text.ToString().Trim();
        int toDepID = Convert.ToInt32(ddlToDep.SelectedValue);
        string toUserName = Request.Form["ddlToUserName"].ToString();
        string opreraterID = Session["userName"].ToString();
        string AlertMsg = "";
        Boolean success = false;
        //向下传递处理
        if (chkFinish.Checked == false)
        {            
            if (annotate == "")
            {
                AlertMsg += "请填写审核批注！";                
            }
            if(toDepID==-1)
            {
                AlertMsg += "请选择部门!";
            }
            if (toUserName == "-1")
            {
                AlertMsg += "请选择审核人";
 
            }
            if (AlertMsg != "")
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('" + AlertMsg + "');", true);

            }
            else
            {
                YCSteps YCStep = new YCSteps();
                YCStep.YCID = YCID;
                YCStep.Annotate = annotate;
                YCStep.ToUserName = toUserName;
                YCStep.EndDate = DateTime.Now;
                YCStep.OperatorID = opreraterID;
                YCStep.Status = "1";
                success = YCStep.AddYCSteps() && YCStep.SendMsgToNextUser() && YCStep.UpdateCurrentOperater();

                if (success == true)
                {
                    Response.Write("<script language='JavaScript'>alert('处理成功！');location.href='CheckYCList.aspx';</script>");

                }
            }
        }
        //完成处理
        if (chkFinish.Checked == true)
        {
            if (annotate == "")
            {
                AlertMsg += "请填写审核批注！";                
            }
            if (AlertMsg != "")
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "", "alert('" + AlertMsg + "');", true);

            }
            else
            {
                YCSteps YCStep = new YCSteps();
                YCStep.YCID = YCID;
                YCStep.Annotate = annotate;
                YCStep.ToUserName = "";
                YCStep.EndDate = DateTime.Now;
                YCStep.OperatorID = opreraterID;
                YCStep.Status = "1";
                success = YCStep.AddYCSteps() && YCStep.UpdateYCStatus();
                if (success == true)
                {
                    Response.Write("<script language='JavaScript'>alert('处理成功！');location.href='CheckYCList.aspx';</script>");
                }
            }

        }
    }
    protected void chkFinish_CheckedChanged(object sender, EventArgs e)
    {
        if (chkFinish.Checked == true)
        {
            ddlToDep.Enabled = false;
            ddlToUserName.Enabled = false;            
        }
        else
        {
            ddlToDep.Enabled = true;
            ddlToUserName.Enabled = true;            
        }
    }
    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        Response.Redirect("ModifyYCAnnotate.aspx?ycid="+lblYCID.Text.Trim());
    }    
}
